package com.example.chatzsyproject.fragment;

import android.animation.Animator;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.chatzsyproject.R;
import com.example.chatzsyproject.adapter.MessageAdapter;
import com.example.chatzsyproject.base.ForResultNestedCompatFragment;
import com.example.chatzsyproject.model.MessageModel;
import com.example.chatzsyproject.ui.ChatActivity;
import com.example.chatzsyproject.utils.AnimUtil;
import com.example.chatzsyproject.utils.Constant;
import com.example.chatzsyproject.utils.Utils;
import com.example.chatzsyproject.view.AZListView.azlist.AZTitleDecoration;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class FragmentOne extends ForResultNestedCompatFragment {
    private View rootView;
    private Unbinder unbinder;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.im_right)
    ImageView im_right;

    MessageAdapter mAdapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private List<MessageModel> list = new ArrayList<>();

    private PopupWindow mPopupWindow;
    private AnimUtil animUtil;
    private float bgAlpha = 1f;
    private boolean bright = false;
    private static final long DURATION = 500;
    private static final float START_ALPHA = 0.7f;
    private static final float END_ALPHA = 1f;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_one, null);
        }
        unbinder = ButterKnife.bind(this, rootView);
        initView(rootView);// 控件初始化
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
        return rootView;
    }

    private void initView(View view) {
        tv_title.setText("微信");
        im_right.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new AZTitleDecoration(new AZTitleDecoration.TitleAttributes(getActivity())));
        mAdapter = new MessageAdapter(R.layout.adapter_message, list);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //点击事件
                Intent intent = new Intent();
                intent.setClass(getActivity(), ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, list.get(position).getName());
                if (list.get(position).getChat_type() == 0) {
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                    intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                } else {
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.GroupChat);
                    intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                }
                startActivity(intent);

                String from = list.get(position).getId();
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(from);
                conversation.markAllMessagesAsRead();
                list.get(position).setNum(0);
                mAdapter.notifyDataSetChanged();
            }
        });
        im_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPop();
                toggleBright();
            }
        });
        mPopupWindow = new PopupWindow(getActivity());
        animUtil = new AnimUtil();
        getData();
        setEMMessageListener();
    }

    private void setEMMessageListener() {
        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                for (EMMessage lastMessage : messages) {

                    MessageModel mm = new MessageModel();
                    mm.setName(lastMessage.getUserName());
                    mm.setIma("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571393683260&di=267ddeeb32090e302ed81b6f7657135c&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201811%2F20%2F20181120201929_oitqg.jpg");
                    mm.setTime(Utils.timeStamp2Date(lastMessage.getMsgTime(), "yyyy-MM-dd HH:mm:ss"));

                    String from = lastMessage.getFrom();
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(from);
                    mm.setNum(conversation.getUnreadMsgCount());
                    mm.setId(lastMessage.getFrom());

                    EMMessage.ChatType chatType = lastMessage.getChatType();
                    if (chatType == EMMessage.ChatType.Chat) {
                        mm.setChat_type(0);
                        EMMessage.Type type = lastMessage.getType();
                        switch (type) {
                            case TXT://文本
                                EMTextMessageBody emTextMessageBody = (EMTextMessageBody) lastMessage.getBody();
                                String message = emTextMessageBody.getMessage();
                                mm.setContent(message);
                                break;
                            case IMAGE://图片
                                mm.setContent("图片");
                                break;
                            case VOICE://语音
                                mm.setContent("语音");
                                break;
                            case VIDEO://视频
                                mm.setContent("视频");
                                break;
                        }

                    } else if (chatType == EMMessage.ChatType.GroupChat) {
                        mm.setChat_type(1);
                        EMMessage.Type type = lastMessage.getType();
                        switch (type) {
                            case TXT://文本
                                EMTextMessageBody emTextMessageBody = (EMTextMessageBody) lastMessage.getBody();
                                String message = emTextMessageBody.getMessage();
                                mm.setContent(message);
                                break;
                            case IMAGE://图片
                                mm.setContent("图片");
                                break;
                            case VOICE://语音
                                mm.setContent("语音");
                                break;
                            case VIDEO://视频
                                mm.setContent("视频");
                                break;
                        }
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getId().equals(lastMessage.getFrom())) {
                            list.remove(i);
                            break;
                        }
                    }
                    list.add(0, mm);
                    handler.sendEmptyMessage(1);
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                //消息被撤回
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        });
    }

    private void getData() {
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        Set<String> conversations_key = conversations.keySet();
        for (String s : conversations_key) {
            EMMessage lastMessage = conversations.get(s).getLastMessage();
            MessageModel mm = new MessageModel();
            mm.setName(lastMessage.getUserName());
            mm.setIma("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571393683260&di=267ddeeb32090e302ed81b6f7657135c&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201811%2F20%2F20181120201929_oitqg.jpg");
            mm.setTime(Utils.timeStamp2Date(lastMessage.getMsgTime(), "yyyy-MM-dd HH:mm:ss"));

            String from = lastMessage.getTo();
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(from);
            if (conversation == null) {
                return;
            }
            mm.setNum(conversation.getUnreadMsgCount());
            mm.setId(lastMessage.getFrom());

            EMMessage.ChatType chatType = lastMessage.getChatType();
            if (chatType == EMMessage.ChatType.Chat) {
                mm.setChat_type(0);
                EMMessage.Type type = lastMessage.getType();
                switch (type) {
                    case TXT://文本
                        EMTextMessageBody emTextMessageBody = (EMTextMessageBody) lastMessage.getBody();
                        String message = emTextMessageBody.getMessage();
                        mm.setContent(message);
                        break;
                    case IMAGE://图片
                        mm.setContent("图片");
                        break;
                    case VOICE://语音
                        mm.setContent("语音");
                        break;
                    case VIDEO://视频
                        mm.setContent("视频");
                        break;
                }

            } else if (chatType == EMMessage.ChatType.GroupChat) {
                mm.setChat_type(1);
                EMMessage.Type type = lastMessage.getType();
                switch (type) {
                    case TXT://文本
                        EMTextMessageBody emTextMessageBody = (EMTextMessageBody) lastMessage.getBody();
                        String message = emTextMessageBody.getMessage();
                        mm.setContent(message);
                        break;
                    case IMAGE://图片
                        mm.setContent("图片");
                        break;
                    case VOICE://语音
                        mm.setContent("语音");
                        break;
                    case VIDEO://视频
                        mm.setContent("视频");
                        break;
                }
            }
            list.add(mm);
        }
    }

    private void showPop() {
        // 设置布局文件
        mPopupWindow.setContentView(LayoutInflater.from(getActivity()).inflate(R.layout.pop_conversation_add, null));
        // 为了避免部分机型不显示，我们需要重新设置一下宽高
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置pop透明效果
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
        // 设置pop出入动画
        mPopupWindow.setAnimationStyle(R.style.pop_add);
        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
        mPopupWindow.setFocusable(true);
        // 设置pop可点击，为false点击事件无效，默认为true
        mPopupWindow.setTouchable(true);
        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
        mPopupWindow.setOutsideTouchable(true);
        // 相对于 + 号正下面，同时可以设置偏移量
        mPopupWindow.showAsDropDown(im_right, -100, 0);
        // 设置pop关闭监听，用于改变背景透明度
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                toggleBright();
            }
        });
    }

    private void toggleBright() {
        // 三个参数分别为：起始值 结束值 时长，那么整个动画回调过来的值就是从0.5f--1f的
        animUtil.setValueAnimator(START_ALPHA, END_ALPHA, DURATION);
        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
            @Override
            public void progress(float progress) {
                // 此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
                bgAlpha = bright ? progress : (START_ALPHA + END_ALPHA - progress);
                backgroundAlpha(bgAlpha);
            }
        });
        animUtil.addEndListner(new AnimUtil.EndListener() {
            @Override
            public void endUpdate(Animator animator) {
                // 在一次动画结束的时候，翻转状态
                bright = !bright;
            }
        });
        animUtil.startAnimator();
    }

    /**
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
